package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.UserSearchHistoryService;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 和用户搜索历史  相关
 */
@Service
@Slf4j
public class UserSearchHistoryServiceImpl implements UserSearchHistoryService {

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 异步保存搜索记录
     * @param dto
     * @param userid  当前用户id
     */
    @Override
    @Async//标注当前方法是异步方法
    public void insert(UserSearchDto dto, Integer userid) {

        log.info("异步记录搜索关键字  线程名词:{}", Thread.currentThread().getName());
        //1.校验
        if(dto==null || userid ==null || StringUtils.isBlank(dto.getSearchWords())){
            return;
        }

        //2.查询该用户 之前是否记录过该关键字   查询mongodb
        //select * from ap_user_search where keyword='xxxx' and userId='xxxx';
        Query query = Query.query(Criteria.where("keyword").is(dto.getSearchWords()).and("userId").is(userid));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //3.如果用户之前记录过该关键字  更新创建时间
        if(apUserSearch!=null){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);//save 既可以新增又可以修改，判断条件就是主键是否重复
            return;
        }


        //4.如果用户之前没有搜索过该关键字   新增该关键字
        // 新增前判断该用户是否已经存在10个搜索关键字  如果超过10个则替换最后一个，不超过10个则新增
        //select * from ap_user_search where userId='xxxx' order by createdTime desc
        Query queryParam = Query.query(Criteria.where("userId").is(userid))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(queryParam, ApUserSearch.class);
        if(list==null || list.size()<10){//说明该用户的搜索关键字 不到10个
            //新增
            ApUserSearch as = new ApUserSearch();
            as.setUserId(userid);
            as.setKeyword(dto.getSearchWords());
            as.setCreatedTime(new Date());
            mongoTemplate.save(as);
        }else{
            //替换最后一个
            ApUserSearch userSearch = list.get(list.size() - 1);// 获取该用户下  时间最久的那个搜索关键词
            userSearch.setCreatedTime(new Date());
            userSearch.setKeyword(dto.getSearchWords());
            mongoTemplate.save(userSearch);//走的修改
        }

    }


    @Override
    public ResponseResult load() {
        //1.校验
        WmUser user = WmThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.okResult(null);//只是搜索记录 不展示     但是不能影响用户搜索文章  查看文章详情的行为
            //如果返回需要登陆，前端可能会跳转到登陆页码
        }

        //2.查询mongodb 当前用户  搜索记录

        Query query = Query.query(Criteria.where("userId").is(user.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);


        //3.返回
        return ResponseResult.okResult(apUserSearches);
    }


    @Override
    public ResponseResult del(HistorySearchDto dto) {
        //1.校验
        if (dto==null || StringUtils.isBlank(dto.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询mongodb校验id是否正确
        ApUserSearch userSearch = mongoTemplate.findById(dto.getId(), ApUserSearch.class);
        if(userSearch== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //删除只能删除自己的搜索记录
        if(!userSearch.getUserId().equals(user.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }


        //2.根据id删除   操作mongodb
        //delete from ap_user_search where id =xxxx and userId=xxxx
        Query query = Query.query(Criteria.where("id").is(dto.getId()).and("userId").is(user.getId()));
        DeleteResult result = mongoTemplate.remove(query, ApUserSearch.class);
        log.info("删除条数  {} ",result.getDeletedCount());

        //3.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
